package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseTeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 师资管理类接口
 */
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Autowired
    private CourseBaseMapper courseBaseMapper;



    /**
     * 师资查询接口
     * @param courseId
     * @return
     */
    @Override
    public List<CourseTeacher> getCourseTeacher(Long courseId) {

        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        return courseTeachers;
    }

    /**
     * 添加/修改师资
     * @param courseTeacher
     * @return
     */
    @Override
    public CourseTeacher insertCourseTeacher(CourseTeacher courseTeacher,Long companyId) {

        //先进行数据的合法性校验--只允许向机构自己的课程中添加老师。
        //获取课程id
        Long courseId = courseTeacher.getCourseId();
        //通过课程id获取此课程对应的机构id
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        Long companyId1 = courseBase.getCompanyId();
        if (companyId1 != companyId){
            throw new XueChengPlusException("只允许本机构的相关人员操作！");
        }else {
            //添加/修改老师信息
            CourseTeacher teacher = courseTeacherMapper.selectById(courseTeacher.getId());

            if (teacher == null){   //添加
                courseTeacher.setCreateDate(LocalDateTime.now());
                courseTeacherMapper.insert(courseTeacher);
            } else {    //修改
                courseTeacherMapper.updateById(courseTeacher);
                courseTeacher.setCreateDate(teacher.getCreateDate());
            }

        }

        return courseTeacher;
    }


    /**
     * 师资删除接口
     * @param courseId
     * @param id
     * @param companyId
     * @return
     */
    @Override
    public void delCourseTeacher(Long courseId, Long id, Long companyId) {

        //先进行数据的合法性校验--只允许向机构自己的课程中删除老师。
        //通过课程id获取此课程对应的机构id
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        Long companyId1 = courseBase.getCompanyId();
        if (companyId1 != companyId){
            throw new XueChengPlusException("只允许本机构的相关人员操作！");
        }else {
            //删除老师信息
            courseTeacherMapper.deleteById(id);
        }
    }
}
